package com.learner.ucenter.service.impl;

import com.learner.pojo.user.Group;
import com.learner.pojo.user.GroupMessage;
import com.learner.pojo.user.GroupUser;
import com.learner.pojo.user.vo.MyGroupInfoQueryVo;
import com.learner.pojo.user.vo.MyGroupResultVo;
import com.learner.pojo.user.vo.RecentGroupQueryVo;
import com.learner.pojo.user.vo.RecentGroupVo;
import com.learner.pojo.user.vo.SimpleUser;
import com.learner.pojo.user.vo.ValidateMessageResponseVo;
import com.learner.ucenter.repository.GroupMessageDao;
import com.learner.ucenter.repository.GroupUserDao;
import com.learner.ucenter.service.GroupUserService;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
* @author ice2020x
* @Date: 2023/3/3
* @Description: 获取群聊
**/
@Service
public class GroupUserServiceImpl implements GroupUserService {
    @Resource
    private MongoTemplate mongoTemplate;

    @Autowired
    private GroupUserDao groupUserDao;

    @Autowired
    private GroupMessageDao groupMessageDao;

    @Override
    public List<MyGroupResultVo> getGroupUsersByUserName(String userId) {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("userId").is(userId)),
                Aggregation.lookup(
                        "groups",
                        "groupId",
                        "gid",
                        "groupInfo"
                )
        );

        List<MyGroupResultVo> groupusers = mongoTemplate.aggregate(aggregation, "groupUsers", MyGroupResultVo.class).getMappedResults();
        return groupusers;
    }


    @Override
    public List<MyGroupResultVo> getRecentGroup(RecentGroupVo recentGroupVo) {
        List<ObjectId> groupIds = new ArrayList<>();
        for (String son : recentGroupVo.getGroupIds()) {
            groupIds.add(new ObjectId(son));
        }
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.lookup(
                        "groups",
                        "groupId",
                        "_id",
                        "groupList"
                ), Aggregation.match(Criteria.where("groupId").in(groupIds).and("userId").is(new ObjectId(recentGroupVo.getUserId())))
        );
        List<RecentGroupQueryVo> groupusers = mongoTemplate.aggregate(aggregation, "groupUsers", RecentGroupQueryVo.class).getMappedResults();
        List<MyGroupResultVo> res = new ArrayList<>();
        MyGroupResultVo item;
        for (RecentGroupQueryVo son : groupusers) {
            item = new MyGroupResultVo();
            BeanUtils.copyProperties(son, item);
            res.add(item);
        }
        return res;
    }


    @Override
    public List<MyGroupResultVo> getGroupUsersByGroupId(String groupId) {
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(Criteria.where("groupId").is(new ObjectId(groupId))),
                Aggregation.lookup(
                        "users",
                        "userId",
                        "_id",
                        "userList"
                )
        );
        // 根据群id查询所有群成员消息
        List<MyGroupInfoQueryVo> queryVoList = mongoTemplate.aggregate(aggregation, "groupUsers", MyGroupInfoQueryVo.class).getMappedResults();
        List<MyGroupResultVo> res = new ArrayList<>();
        MyGroupResultVo item;
        for (MyGroupInfoQueryVo son : queryVoList) {
            item = new MyGroupResultVo();
            BeanUtils.copyProperties(son, item);
            item.setUserInfo(new SimpleUser());
            BeanUtils.copyProperties(son.getUserList().get(0), item.getUserInfo());
            res.add(item);
        }
        return res;
    }


    @Override
    public void addNewGroupUser(ValidateMessageResponseVo validateMessage) {
        GroupUser groupUser = groupUserDao.findGroupUserByUserIdAndGroupId(validateMessage.getSenderId(), validateMessage.getGroupInfo().getGid());
        if (groupUser == null) {
            groupUser = new GroupUser();
            groupUser.setGroupId(validateMessage.getGroupInfo().getGid());
            groupUser.setUserId(validateMessage.getSenderId());
            groupUser.setUsername(validateMessage.getSenderName());
            groupUserDao.save(groupUser);

            Update update = new Update();
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(groupUser.getGroupId()));
            //群人数加1
            mongoTemplate.upsert(query, update.inc("userNum", 1), Group.class);
            //添加一条群消息
            GroupMessage groupMessage = new GroupMessage();
            groupMessage.setRoomId(groupUser.getGroupId().toString());
            //设置发送者id，为了退出群聊时比较方便删除!!!
            groupMessage.setSenderId(validateMessage.getSenderId());
            groupMessage.setMessageType("sys");
            groupMessage.setMessage(groupUser.getUsername() + "加入群聊");
            groupMessageDao.save(groupMessage);
        }
    }
}